package com.example.keepmesafe.activities;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.example.keepmesafe.R;
import com.example.keepmesafe.adapters.InitialiseTagsAdapter;
import com.example.keepmesafe.domain.Tag;
import com.example.keepmesafe.repository.DBHelper;
import com.example.keepmesafe.service.AESCrypto;
import com.example.keepmesafe.service.DataXmlExporter;
import com.example.keepmesafe.service.impl.DataXmlExporterImpl;

public class UserHome extends Activity{
	static final String LOG_TAG = "UserHome";
	private static final int DIALOG_ADD_TAG = 10;
	private static final int DIALOG_EXPORT_CONFIRM = 11;
	final Context ctx = this;
    final DBHelper tagStorageImpl = new DBHelper(ctx);
    String masterPass;
    final AESCrypto crypto = new AESCrypto();
   
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(LOG_TAG, "onCreate");
		setContentView(R.layout.activity_user_home);
		
		SQLiteDatabase tagDB =  tagStorageImpl.getReadableDatabase();
		Cursor authUser = tagDB.rawQuery("select * from auth", null);
		masterPass = getMasterFromCursor(authUser);
		if(masterPass.equals("empty"))
			 Toast.makeText(ctx, "No Master", Toast.LENGTH_SHORT).show();
		tagDB.close();
		
	}
	
	@Override
	public void onPause(){
		super.onPause();
		killApp();
	}
	
	@Override
	public void onBackPressed() {
	
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		refreshList();
	}
	
	protected void onStop(){
		super.onStop();
		killApp();
	}
	
	@Override
	protected void onRestart(){
		super.onRestart();
		startActivity(new Intent(ctx,UserLogin.class));
	}
	
	public void refreshList(){
		 new LoadTagsFromDatabase().execute();
	}
	
	public String getMasterFromCursor(Cursor authUser){  
			
			while(authUser.moveToNext()){
				return authUser.getString(1);
			}
			return "empty";
	}
	
	public void killApp(){
		 new Timer().schedule(new TimerTask(){
			    public void run() { 
			    	startActivity(new Intent(ctx,UserLogin.class));
			    }
		}, 12000000);
	}
	
   @Override
    public boolean onCreateOptionsMenu(Menu menu) {
     MenuInflater inflater = getMenuInflater();
     inflater.inflate(R.menu.homeactionbar, menu);
     return super.onCreateOptionsMenu(menu);
   }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    // action with ID action_refresh was selected
	    case R.id.addTag:
	    	showDialog(DIALOG_ADD_TAG);
	      break;
	    case R.id.logout:
	    	  Intent i = new Intent(ctx,UserLogin.class);
	    	  startActivity(i);
		      break; 
	    case R.id.exportTags:
	    	showDialog(DIALOG_EXPORT_CONFIRM); 
		      break;
	    default:
	    	return super.onOptionsItemSelected(item);
	    }

	    return true;
	  }
    
    @Override
	protected Dialog onCreateDialog(int id) {
	    AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
	    // Get the layout inflater
	    LayoutInflater inflater = LayoutInflater.from(ctx);
	    if(id==10){
	    final View dialogView = inflater.inflate(R.layout.createtaglayout, null);
	    
	    // Pass null as the parent view because its going in the dialog layout
	    builder.setView(dialogView)
	    // Add action buttons
	           .setPositiveButton(R.string.btnAddTag, new DialogInterface.OnClickListener() {
	               @Override
	               public void onClick(DialogInterface dialog, int id) {
	            	   persistTagToDatabase(dialogView);
	            	   dialog.dismiss();
	               }
	           })
	           .setNegativeButton(R.string.btnCancel, new DialogInterface.OnClickListener() {
	               public void onClick(DialogInterface dialog, int id) {
	            	   dialog.dismiss();
	               }
	           }); 
	    }else if(id == 11){
	    	builder.setTitle("Export Data Confirmation?")
	    			.setMessage("Exporting tags will save all Tags to a file saved on device and will delete entire database\nWould you like to proceed?")
	    			.setPositiveButton("Proceed", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							new ExportTagsFromDatabase().execute();
						}
					})
					.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.dismiss();
						}
					});
	    }
	    return builder.create();
	}
    
	public void persistTagToDatabase(View dialogView){
		Log.d(LOG_TAG, "persistTagToDatabase");
		SQLiteDatabase tagDB =  tagStorageImpl.getWritableDatabase();
		Tag newTag = setTagFromTextViews(dialogView);
		if(newTag!=null){
			ContentValues tagValues = new ContentValues(3);
			tagValues.put("tagName", newTag.getTagName());
			tagValues.put("tagUsername", newTag.getTagUsername());
			tagValues.put("tagPasword", newTag.getTagPassword());
			
			tagDB.insertOrThrow("tag",null, tagValues);
			tagDB.close();
			Toast.makeText(ctx, "Tag successfully saved..", Toast.LENGTH_SHORT).show();
		}else{
			Toast.makeText(ctx, "Tag was not created..", Toast.LENGTH_SHORT).show();
		}
		new LoadTagsFromDatabase().execute();
	}
	
	public Tag setTagFromTextViews(View dialogView){
		Log.d(LOG_TAG, "setTagFromTextViews");
		Tag tagToInitialise = new Tag();
		EditText tvTagName = (EditText)dialogView.findViewById(R.id.TagName);
		EditText tvTagUsername = (EditText)dialogView.findViewById(R.id.TagUsername);
		EditText tvTagPassword = (EditText)dialogView.findViewById(R.id.TagPassword );
		
		if((tvTagName.getText().toString()!=null
			&&tvTagUsername.getText().toString()!=null
			&&tvTagPassword.getText().toString()!=null)&&
			(!tvTagName.getText().toString().equals("")
			&&!tvTagUsername.getText().toString().equals("")
			&&!tvTagPassword.getText().toString().equals(""))){
				try {
					tagToInitialise.setTagName(tvTagName.getText().toString());
					tagToInitialise.setTagUsername(tvTagUsername.getText().toString());
					String ecryptedPassword = crypto.encrypt(tvTagPassword.getText().toString());
					tagToInitialise.setTagPassword(ecryptedPassword);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					Log.d(LOG_TAG, "Exception");
					e.printStackTrace();
				}
				tvTagName.setText("");	
				tvTagUsername.setText("");
				tvTagPassword.setText("");
				
		}else{
			Toast.makeText(ctx, "Please ensure all values are entered.", Toast.LENGTH_SHORT).show();
			return null;
		}
		return tagToInitialise;
	}

	private class LoadTagsFromDatabase extends AsyncTask<Void, Void, Void>{
		private ProgressDialog Dialog = new ProgressDialog(ctx);
		SQLiteDatabase tagDB =  tagStorageImpl.getReadableDatabase();
		ArrayList<Tag> mArrayList = new ArrayList<Tag>();
		protected void onPreExecute() {
			Dialog.setMessage("Please wait..");
			Dialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			Cursor results = tagDB.rawQuery("select * from tag order by _id desc", null);
			while(results.moveToNext()){
				Tag temp = new Tag();
				temp.setId(results.getLong(0));
				temp.setTagName(results.getString(1));
				temp.setTagUsername(results.getString(2));
				temp.setTagPassword(results.getString(3));
				mArrayList.add(temp);
			}
			
			results.close();
			tagDB.close();
			return null;
		}
		
		protected void onPostExecute(Void unused) {
			Dialog.dismiss();
			ListView tagListView = (ListView)findViewById(R.id.listview);
			InitialiseTagsAdapter myCustomAdapter = new InitialiseTagsAdapter(ctx, mArrayList,UserHome.this);
			tagListView.setAdapter(myCustomAdapter);
		}
	}

	private class ExportTagsFromDatabase extends AsyncTask<Void, Void, Void>{
		private ProgressDialog Dialog = new ProgressDialog(ctx);
		SQLiteDatabase tagDB =  tagStorageImpl.getWritableDatabase();
		ArrayList<Tag> mArrayList = new ArrayList<Tag>();
		DataXmlExporter dxml = new DataXmlExporterImpl();
		String exportPath;
		
		protected void onPreExecute() {
			Dialog.setMessage("Please wait..");
			Dialog.show();
		}
		@Override
		protected Void doInBackground(Void... params) {
			Cursor results = tagDB.rawQuery("select * from tag order by _id desc", null);
			while(results.moveToNext()){
				Tag temp = new Tag();
				temp.setId(results.getLong(0));
				temp.setTagName(results.getString(1));
				temp.setTagUsername(results.getString(2));
				temp.setTagPassword(results.getString(3));
				mArrayList.add(temp);
			}
			try {
				exportPath = dxml.export(mArrayList);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			results.close();
			return null;
		}
		
		protected void onPostExecute(Void unused) {
			Dialog.dismiss();
			Toast.makeText(ctx, "Amount of Tags exported: "+mArrayList.size() + ".\nThe Path for the exported data is: "+exportPath, Toast.LENGTH_LONG).show();
			Toast.makeText(ctx, "Tags removed: "+tagStorageImpl.deleteAllTags(tagDB),Toast.LENGTH_SHORT).show();
			tagDB.close();
			refreshList();
		}
	}
	
}



